package com.ziyueyuwen.xiniao.service.impl;

import com.alibaba.fastjson.JSON;
import com.ziyueyuwen.xiniao.bean.ao.QuestionForCourseLessonAO;
import com.ziyueyuwen.xiniao.bean.ZyCourseInfo;
import com.ziyueyuwen.xiniao.bean.question.CourseLessonElementData;
import com.ziyueyuwen.xiniao.bean.question.ZyQuestionCourseQuestion;
import com.ziyueyuwen.xiniao.bean.question.ZyQuestionData;
import com.ziyueyuwen.xiniao.bean.vo.ZyQuestionDataVO;
import com.ziyueyuwen.xiniao.dao.ZyHomeworkRecordMapper;
import com.ziyueyuwen.xiniao.dao.ZyQuestionDataMapper;
import com.ziyueyuwen.xiniao.dao.ZyQuestionLessonCourseMapper;
import com.ziyueyuwen.xiniao.enums.LessonModuleEnum;
import com.ziyueyuwen.xiniao.service.CourseService;
import com.ziyueyuwen.xiniao.service.MessageTaskService;
import com.ziyueyuwen.xiniao.service.QuestionCourseService;
import com.ziyueyuwen.xiniao.service.SubjectQuestionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wancheng  on 2019/1/10.
 */
@Service
public class QuestionCourseServiceImpl implements QuestionCourseService {

    private final static Logger logger = LoggerFactory.getLogger(QuestionCourseServiceImpl.class);

    @Autowired
    ZyQuestionLessonCourseMapper zyQuestionLessonCourseMapper;
    @Autowired
    CourseService courseService;
    @Autowired
    ZyQuestionDataMapper zyQuestionDataMapper;
    @Autowired
    SubjectQuestionService subjectQuestionService;
    @Autowired
    ZyHomeworkRecordMapper zyHomeworkRecordMapper;
    @Autowired
    MessageTaskService messageTaskService;

    @Override
    public ZyQuestionCourseQuestion insert(ZyQuestionCourseQuestion question) {
        logger.info("添加题,questionData={}", JSON.toJSON(question));
        zyQuestionLessonCourseMapper.insertUseGeneratedKeys(question);
        return question;
    }

    @Override
    public void insertBatch(List<ZyQuestionCourseQuestion> questions) {
        logger.info("批量保存,questionData={}", JSON.toJSON(questions));
        zyQuestionLessonCourseMapper.insertBatch(questions);
    }

    @Override
    public ZyQuestionCourseQuestion updateByPreKey(ZyQuestionCourseQuestion question) {
        logger.info("修改,questionData={}", JSON.toJSON(question));
        zyQuestionLessonCourseMapper.updateByPrimaryKeySelective(question);
        question = zyQuestionLessonCourseMapper.selectByPrimaryKey(question.getId());
        return question;
    }

    @Override
    public void deleteByPreKey(Integer id) {
        logger.info("删除,id={}", id);
        zyQuestionLessonCourseMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByBean(ZyQuestionCourseQuestion bean) {
        logger.info("根据bean删除,bean={}", JSON.toJSON(bean));
        zyQuestionLessonCourseMapper.delete(bean);
    }

    @Override
    public List<ZyQuestionCourseQuestion> getByObject(ZyQuestionCourseQuestion question) {
        return zyQuestionLessonCourseMapper.select(question);
    }

    @Override
    public List<ZyQuestionCourseQuestion> getByCourseId(Integer courseId) {
        ZyQuestionCourseQuestion params = new ZyQuestionCourseQuestion();
        params.setCourseId(courseId);
        List<ZyQuestionCourseQuestion> res = zyQuestionLessonCourseMapper.select(params);
        return res;
    }

    @Override
    public List<CourseLessonElementData> getCourseDetails(Integer courseId) {
        ZyCourseInfo course = courseService.getByPreKey(courseId);
        List<ZyQuestionCourseQuestion> questions = getByCourseId(courseId);
        // key:lessonIndex
        Map<Integer, List<ZyQuestionCourseQuestion>> indexQuestionMap = questions.stream().collect(Collectors.groupingBy(ZyQuestionCourseQuestion::getLessonIndex));
        List<CourseLessonElementData> res = new ArrayList<>();
        for (int index = 1; index <= course.getLessonCount(); index++) {
            CourseLessonElementData element = new CourseLessonElementData();
            element.setCourseId(courseId);
            element.setIndex(index);
            List<ZyQuestionCourseQuestion> details = indexQuestionMap.get(index);
            if (!CollectionUtils.isEmpty(details)) {
                //key : type
                Map<LessonModuleEnum, List<ZyQuestionCourseQuestion>> typeQuestion = details.stream().collect(Collectors.groupingBy(ZyQuestionCourseQuestion::getLessonQuestionType));
                if (!CollectionUtils.isEmpty(typeQuestion.get(LessonModuleEnum.PREVIEW))) {
                    element.setPreview(true);
                }
                if (!CollectionUtils.isEmpty(typeQuestion.get(LessonModuleEnum.HOMEWORK))) {
                    element.setHomework(true);
                }
                if (!CollectionUtils.isEmpty(typeQuestion.get(LessonModuleEnum.SUMMARY))) {
                    element.setSummary(true);
                }
                if (!CollectionUtils.isEmpty(typeQuestion.get(LessonModuleEnum.EXPAND))) {
                    element.setExpand(true);
                }
                if (!CollectionUtils.isEmpty(typeQuestion.get(LessonModuleEnum.CLASSROOM_TEST))) {
                    element.setClassRoomTest(true);
                }
            }
            res.add(element);
        }
        res.stream().sorted((o1, o2) -> o1.getIndex() - o2.getIndex());
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ZyQuestionData> updateQuestionForCourseLesson(QuestionForCourseLessonAO updateData) throws Exception{
        if (!CollectionUtils.isEmpty(messageTaskService.getByCourseIdAndLessonIndex(updateData.getCourseId(),updateData.getLessonIndex(),updateData.getLessonQuestionType()))){
            throw new Exception("当前作业已发布,无法修改");
        }
        logger.info("修改,QuestionForCourseLessonAO={}", JSON.toJSON(updateData));
        //先删除原有的数据
        ZyQuestionCourseQuestion deleteParam = new ZyQuestionCourseQuestion();
        deleteParam.setCourseId(updateData.getCourseId());
        deleteParam.setLessonIndex(updateData.getLessonIndex());
        deleteParam.setLessonQuestionType(updateData.getLessonQuestionType());
        if (updateData.getQuestionGroup() == null || updateData.getQuestionGroup() == 0){
            deleteParam.setQuestionGroup(0);
        }else{
            deleteParam.setQuestionGroup(updateData.getQuestionGroup());
        }
        deleteByBean(deleteParam);
        //批量添加
        if (!CollectionUtils.isEmpty(updateData.getQuestionDataId())){
            List<ZyQuestionCourseQuestion> needInsert = new ArrayList<>();
            for (Integer questionId: updateData.getQuestionDataId()) {
                ZyQuestionData questionData = zyQuestionDataMapper.selectByPrimaryKey(questionId);
                if (questionData == null){
                    throw new Exception("id为"+questionId+"的 题型为空");
                }
                ZyQuestionCourseQuestion data = new ZyQuestionCourseQuestion();
                data.setCourseId(updateData.getCourseId());
                data.setLessonIndex(updateData.getLessonIndex());
                data.setLessonQuestionType(updateData.getLessonQuestionType());
                data.setQuestionDataId(questionId);
                data.setCreateTime(new Date());
                if (updateData.getQuestionGroup() == null){
                    data.setQuestionGroup(0);
                }else{
                    data.setQuestionGroup(updateData.getQuestionGroup());
                }
                needInsert.add(data);
            }
            if (!CollectionUtils.isEmpty(needInsert)){
                insertBatch(needInsert);
            }
        }
        subjectQuestionService.saveSubjectQuestion(updateData.getCourseId(), updateData.getLessonIndex(), updateData.getAnswerOrder());
        return null;
    }

    @Override
    public List<ZyQuestionDataVO> getQuestionOfCourseLesson(Integer courseId, Integer lessonIndex, LessonModuleEnum type) {

        List<ZyQuestionDataVO> data = zyQuestionDataMapper.getQuestionDataOfCourseLesson(courseId,lessonIndex,type,null);
        data.forEach(
                q->{
                    q.setGradeValue(q.getGrade().getDescription());
                }
        );
        return data;
    }

    @Override
    public List<ZyQuestionDataVO> getQuestionOfCourseLesson(Integer courseId, Integer lessonIndex, LessonModuleEnum type, Integer questionGroup) {

        List<ZyQuestionDataVO> data = zyQuestionDataMapper.getQuestionDataOfCourseLesson(courseId,lessonIndex,type,questionGroup);
        data.forEach(
                q->{
                    q.setGradeValue(q.getGrade().getDescription());
                }
        );
        return data;
    }
}
